import { Injectable, UnauthorizedException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../login/entities/login.entity';
import * as jwt from 'jsonwebtoken';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class TokenService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private readonly configService: ConfigService,
  ) {}

  // 生成并保存refreshToken
  async generateAndSaveToken(userId: string): Promise<string> {
    const user = await this.userRepository.findOne({ where: { id: userId } });
    if (!user) throw new NotFoundException('用户不存在');
    const secret = this.configService.get<string>('JWT_SECRET');
    const token = jwt.sign({ username: user.username }, secret, { expiresIn: '7d' });
    user.refreshToken = token;
    await this.userRepository.save(user);
    return token;
  }

  // 更新refreshToken
  async updateToken(userId: string): Promise<string> {
    return this.generateAndSaveToken(userId);
  }

  // 删除refreshToken
  async deleteToken(userId: string): Promise<void> {
    const user = await this.userRepository.findOne({ where: { id: userId } });
    if (!user) throw new NotFoundException('用户不存在');
    user.refreshToken = null;
    await this.userRepository.save(user);
  }

  // 验证refreshToken
  async validateToken(token: string): Promise<boolean> {
    const secret = this.configService.get<string>('JWT_SECRET');
    try {
      const payload = jwt.verify(token, secret) as any;
      const user = await this.userRepository.findOne({ where: { username: payload.username, refreshToken: token } });
      if (!user) throw new UnauthorizedException('无效token');
      return true;
    } catch (e) {
      throw new UnauthorizedException('token校验失败');
    }
  }
} 